package top.lyunz.fangkeji.config;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import top.lyunz.fangkeji.bean.Fuser;

@Component
public class Interceptor implements HandlerInterceptor {

	// 这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws IOException {
		// 每一个项目对于登陆的实现逻辑都有所区别，我这里使用最简单的Session提取User来验证登陆。
		HttpSession session = request.getSession();
		// 这里的User是登陆时放入session的
		Fuser fuser = (Fuser) session.getAttribute("user");
		// 如果session中没有user，表示没登陆
		if (fuser == null) {
			//System.out.println(request.getRequestURL());
			if (request.getRequestURL().indexOf("/web/")!=-1) {
				response.sendRedirect("/redirect/tologin");
				return false;
			}else if(request.getRequestURL().indexOf("/wechat/")!=-1){
				response.sendRedirect("/redirect/sessionisnull");
				return false;
			}
			return false;
		} else {
			// 如果session里有user，表示该用户已经登陆，放行，用户即可继续调用自己需要的接口
			//System.out.println(request.getRequestURL());
			return true;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable Exception ex) throws Exception {
	}
}
